<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @open="getRoleList" @close="handleClose">
    <!-- 角色列表 -->
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <!-- label控制选中ID -->
      <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { reqGetRoleList } from '@/api/setting.js'
import { getDetailInfo as reqGetUserDetailById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    //   选中角色Ids
    userId: {
      type: String,
      required: true
    },
    showRoleDialog: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      // 选中角色
      roleIds: [],
      //   所有角色
      allRoles: []
    }
  },
  methods: {
    async assignRole() {
      const ret = await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      if (ret.code === 10000) {
        this.$message.success('更新角色列表成功')
        this.handleClose()
      }
    },
    //   获取角色列表
    getRoleList() {
      this.loading = true
      this.$nextTick(() => { this.showRoleDialog = true })
      // this.$nextTick(() => { this.$emit('update:showRoleDialog', true) })
      const info = reqGetUserDetailById(this.userId)
      const ret = reqGetRoleList({ page: 1, pagesize: 10000 })
      Promise.all([info, ret]).then((result) => {
        this.roleIds = result[0].data.roleIds
        this.allRoles = result[1].data.rows
      }).catch(() => {
        this.$message.error('获取角色列表失败')
      }).finally(() => {
        this.loading = false
      })
      //   try {
      //     const info = await reqGetUserDetailById(this.userId)
      //     if (info.code === 10000) {
      //       this.roleIds = info.data.roleIds
      //     } else {
      //       return this.$message.error('获取选中角色列表失败')
      //     }

      //     const ret = await reqGetRoleList({ page: 1, pagesize: 10000 })

    //     if (ret.code === 10000) {
    //       console.log(ret)
    //       this.allRoles = ret.data.rows
    //     }
    //   } catch {
    //     this.$message.error('获取所有角色列表失败')
    //   }
    },
    handleClose () {
      this.roleIds = []
      this.$emit('update:showRoleDialog', false)
      this.allRoles = []
    }
  }
}
</script>
<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
